/*
通过 mutation 间接更新 state 的多个方法的对象
*/
// 接口函数
import {
  reqCompositeIndexNow,
  reqCompositeIndexHistory,
  reqEvent, // 查询报警事件
  reqCustomerEnter, // 获取商超进店人次
  reqViolateRate, // 获取违规率
  reqViolateHistory, // 获取历史违规率
  reqManagerOnlineHistory, // 获取历史站长在站率
  reqStatistic, // 事件统计 strict 版本，可用来统计违规事件数
  reqCIHistory, // 获取拥堵指数
  reqIsleServiceTime, // 获取加油岛历史服务时间
  reqService, //  加油岛服务车辆数和服务时间或超市服务次数和服务时间
  reqStreamQuery, // 获取站点视频流地址
  reqStreamPull, // 请求服务器开始推流
  reqScore, //获取综合得分


  reqVideoList, //获取视频列表
  reqVideoIntergrity, //获取视频完整性
  reqmonitorStatus, //获取摄像头在线情况
} from "@/api";

import dayjs from 'dayjs'
import constData from "@/util/constData"
import constData2 from "@/util/constData2"
// 测试数据
import testData from "@/util/testData"
import {mapTimeList} from '../util/util'
import { SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG } from "constants";

//前端验证用户名密码
const userInfo = {
  userName: '123',
  password: '123',
  token: '123'
}

export default {
  handleLogin({commit},userinfo){
    commit('SET_USER',{userinfo})
    commit('SET_LOGIN_STATUS',true)
    sessionStorage.setItem('user', JSON.stringify(userinfo));
  },

  handleLogout({commit},userinfo){
    commit('SET_USER',{userinfo})
    commit('SET_LOGIN_STATUS',false)
    sessionStorage.removeItem('user');
  },

  // 获取拥堵指数
  async getJamIndexData ({commit}, params) {
    let resData = await reqCIHistory(params)
    let jamIndexData = resData.data
    // console.log("拥堵指数",jamIndexData)
    let timeList = mapTimeList(params.start_time, params.end_time, params.group)
    let jamIndex = []
    jamIndex = timeList.map(time => {
      let timeformat=time
      return {
        value: (jamIndexData[timeformat] * 5).toFixed(2),
        symbolSize: (jamIndexData[timeformat] * 5).toFixed(2) === '0.00' ? 4 : 10,
        label: {
          show: (jamIndexData[timeformat] * 5).toFixed(2) === '0.00' ? false : true
        }
      }
    })
    commit('GETJAMINDEXDATA', {jamIndex})
  },

  // 获取站长在站率
  async getManagerOnlineRate({commit}, params) {
    let resData = await reqManagerOnlineHistory(params)
    let managerOnlineRateGroup = resData.data
    // console.log("经理在线率",managerOnlineRateGroup)
    let timeList = mapTimeList(params.start_time, params.end_time, 'day')
    let getManagerOnlineRateData = {
      managerOnlineRateData: []
    }
    getManagerOnlineRateData.managerOnlineRateData = timeList.map((time)=>{
      let timeformat=time
      return managerOnlineRateGroup[timeformat] ? (managerOnlineRateGroup[timeformat] * 100).toFixed(1) : 0
    })
    commit('GETMANAGERONLINERATE', {getManagerOnlineRateData})
  },

  // 获取加油岛服务时间
  async getHistoryRefuelServiceTimeData ({commit}, params) {
    let resData = await reqIsleServiceTime(params)
    let refuelServiceTime = resData.data
    console.log('获取 历史加油岛服务时间:', resData, refuelServiceTime)    
    let refuelServiceTimeData = []
    Object.keys(refuelServiceTime).forEach(function(time){
      Object.keys(refuelServiceTime[time]).forEach(function(channelIndex){
        if(isNaN(refuelServiceTimeData[refuelServiceTime[time][channelIndex]["isle"]])) refuelServiceTimeData[refuelServiceTime[time][channelIndex]["isle"]] = 0
        refuelServiceTimeData[refuelServiceTime[time][channelIndex]["isle"]] += refuelServiceTime[time][channelIndex]["time"]
      })
    })
    let refuelServiceIndexName = [] // 加油岛名称
    let refuelServiceIndexTime = [] // 加油岛对应服务时间
    Object.keys(refuelServiceTimeData).forEach(function(isle) {
        refuelServiceIndexName.push(isle + '号')
        refuelServiceIndexTime.push((refuelServiceTimeData[isle]).toFixed(2))
    
    })
    commit('GETHISTORYREFUELSERVICETIMEDATA', {refuelServiceIndexName, refuelServiceIndexTime})
  },

  // 加油岛或超市服务数据
  async getServiceTimeData({commit},params){
    let result = await reqService(params)
    let resData = result.data
    // console.log("服务数据",resData)
    let timeList = mapTimeList(params.start_time, params.end_time, params.group)
    let serviceData = {
      serviceAverageTime:[],
      serviceCount:[],
      serviceTotalCount:0,
      serviceTotalTime:0,
      serviceTotalAverageTime:0,
      category:params.category
    }
    serviceData.serviceTotalTime = resData.time_all
    serviceData.serviceTotalCount = resData.count_all
    serviceData.serviceTotalAverageTime = Number((resData.average_all/60).toFixed(1))
    serviceData.serviceAverageTime = timeList.map((time)=>{
      return resData.count_group[time] ? (resData.count_group[time].average_time/60).toFixed(2) : 0
    })
    serviceData.serviceCount = timeList.map((time)=>{
      return resData.count_group[time] ? resData.count_group[time].total_num : 0
    })
    // console.log("处理后的服务数据",serviceData)
    commit('GETSERVICETIMEDATA',{serviceData})
  },

   // 获取商超进店人次
   async getCustomerEnter({commit}, params) {
    let resData = await reqCustomerEnter(params)
    let customerEnterDataGroup = resData.data.count_group
    let timeList = mapTimeList(params.start_time, params.end_time, params.group)
    let getCustomerEnterData = {
      enterPersonsSum: 0, // 进店总人次
      enterPersonsData: [], // 进店人次分布
    }
    getCustomerEnterData.enterPersonsSum = Math.round(resData.data.count_all)
    getCustomerEnterData.enterPersonsData = timeList.map((time)=>{
      return customerEnterDataGroup[time] ? Math.round(customerEnterDataGroup[time]) : 0
    })
    commit('GETCUSTOMERENTER', {getCustomerEnterData})
  },

  //获取违规率
  async getViolateRate({commit},params){
    console.log(params)
    let result = await reqViolateRate(params)
    let resData = result.data
    let violateRateData = {
      category:params.category,
      violateRate:resData.general
    }
    commit('GETVIOLATERATE',{violateRateData})
  },

  // 获取加油站违规事件数据
  async getViolateEventData ({commit}, params) {
    let resData = await reqStatistic(params)
    let violateEventData = resData.data.categorys;
    let violateData = {
      checkoutSum: 0, // 便利店违规事件总数
      refuelSum: 0, // 加油区违规事件总数
      safeboxSum: 0, // 保险柜违规事件总数
      unloadSum: 0, // 卸油口违规事件总数
      checkoutVE: [], // 便利店违规事件
      refuelVE: [], // 加油区违规事件
      safeboxVE: [], // 保险柜违规事件
      unloadVE: [] // 卸油口违规事件
    }

    violateData.checkoutSum = violateEventData["checkout"].group.total_num;
    violateData.refuelSum = violateEventData["refuel_side"].group.total_num;
    violateData.safeboxSum = violateEventData["safebox"].group.total_num;
    violateData.unloadSum = violateEventData["unload"].group.total_num;

    let checkoutData = violateEventData["checkout"].group
    let refuel_sideData = violateEventData["refuel_side"].group
    let safeboxData = violateEventData["safebox"].group
    let unloadData = violateEventData["unload"].group

    // 映射的时间列表
    let timeList = mapTimeList(params.start_time, params.end_time, params.group)
    timeList.forEach((time)=>{
      violateData.checkoutVE.push(checkoutData[time]?checkoutData[time]:0)
      violateData.refuelVE.push(refuel_sideData[time]?refuel_sideData[time]:0)
      violateData.safeboxVE.push(safeboxData[time]?safeboxData[time]:0)
      violateData.unloadVE.push(unloadData[time]?unloadData[time]:0)
    })
    // console.log("处理后的违规事件数据:",violateData)
    commit('GETVIOLATEEVENTDATA', { violateData })
  },

  // 获取卸油次数，保险柜打开次数，钱箱打开次数
  async getStationCenterCountData ({commit}, params) {
    let resData = await reqStatistic(params)
    let actionsData = resData.data.event_names;
    // console.log('获取卸油次数，保险柜打开次数，钱箱打开次数：', resData, actionsData)

    let countData = {
      unloadCount: 0, // 卸油次数
      safeboxCount: 0, // 保险柜打开次数
      moneyboxCount: 0 // 钱箱打开次数
    }

    countData.safeboxCount = actionsData["开启保险柜"]["total_num"] // 保险柜
    countData.moneyboxCount = actionsData["开启钱箱"]["total_num"] // 钱箱
    countData.unloadCount = actionsData["油罐车到达"]["total_num"] // 卸油次数
    commit('GETSTATIONCENTERCOUNTDATA', { countData })
  },

  // 获取事件表格列表
  async getEventsTableData({commit}, params) {
    let resData = await reqStatistic(params)
    let actionsData = resData.data.event_names;
    let actions = params.event_names.split(',')
    // console.log('获取事件表格列表：', resData, actionsData, actions)

    let eventTableData = actions.map(event => {
      let todayCount = actionsData[event]["group"][dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss")];
      let yestodayCount = actionsData[event]["group"][params.start_time];
      let decreaseCount = "";
      if (yestodayCount - todayCount > 0) {
        decreaseCount = "下降 " + Math.abs(yestodayCount - todayCount) + " 次";
      } else if (yestodayCount - todayCount < 0) {
        decreaseCount = "上升 " + Math.abs(yestodayCount - todayCount) + " 次";
      } else {
        decreaseCount = "持平";
      }
      return {
        eventName: event,
        todayCount,
        yestodayCount,
        decreaseCount
      }
    })
    eventTableData = eventTableData.sort((a, b) => b.todayCount - a.todayCount);
    commit('GETEVENTSTABLEDATA', {eventTableData})
  },

  // 获取各项评分
  async getScore({commit}, params) {
    let resData = await reqScore(params)
    let details = resData.data.details
    details.general = resData.data.general
    let scoreData = details
    // console.log("评分数据",scoreData)
    commit('GETSCORE', {scoreData})
  },

  // 获取 站点评分变化趋势
  async getStationScoreTrendData ({commit}, params) {
    let resData = await reqScore(params)
    let stationScoreGroup = resData.data.group
    let timeList = mapTimeList(params.start_time, params.end_time, 'day')

    let scoreListData = {
      general: [], // 总评分
      safety: [], // 安全评分
      efficiency: [], // 效率评分
      management: [], // 管理评分
      service: [], // 服务评分
      checkout: [], // 便利店
      refuel: [], // 加油区
      safebox: [], // 财务室
      unload: [] // 卸油口
    }
    timeList.forEach((item) => {
      scoreListData.general.push({
        value: Math.round(stationScoreGroup[item]["score"]*100)/100 ,
        // label: {
        //   show: index%2 === 1 ? true : false
        // }
      })
      scoreListData.service.push({
        value: Math.round(stationScoreGroup[item]["details"]["service"]*100)/100
      })
      scoreListData.safety.push({
        value: Math.round(stationScoreGroup[item]["details"]["safety"]*100)/100
      })
      scoreListData.management.push({
        value: Math.round(stationScoreGroup[item]["details"]["management"]*100)/100
      })
      scoreListData.efficiency.push({
        value: Math.round(stationScoreGroup[item]["details"]["efficiency"]*100)/100
      })
      scoreListData.checkout.push({
        value: Math.round(stationScoreGroup[item]["details"]["checkout"]*100)/100
      })
      scoreListData.refuel.push({
        value: Math.round(stationScoreGroup[item]["details"]["checkout"]*100)/100
      })
      scoreListData.safebox.push({
        value: Math.round(stationScoreGroup[item]["details"]["safebox"]*100)/100
      })
      scoreListData.unload.push({
        value: Math.round(stationScoreGroup[item]["details"]["unload"]*100)/100
      })
    })

    // console.log('处理 站点评分变化趋势 后的数据:', scoreListData)
    commit('GETSTATIONSCORETRENDDATA', { scoreListData })
  },
  
  // 更新数据分析界面时间
  updateSelectedDateTime ({commit}, selectedData) {
    // console.log('更新选择的站点数据', selectedData)
    commit('UPDATESELECTEDDATETIME', { selectedData })
  },

   // 获取站点视频流地址
   async getStationVideoStreamUrl({commit}) {
    // 后端读取视频流
    let params = new FormData()
    let resData = await reqStreamQuery(params)
    // console.log('获取 站点视频流地址:',params, resData)
    if(resData.code === 6000) {
      let videoList = resData.data
      videoList.forEach(ele => {
        ele['title'] =  constData.categoryData2[ele.category] + ele.channel + '号视频'
      })
      commit('GETSTATIONVIDEOSTREAMURL', { videoList })
    }else{
      // 获取失败后更新获取的视频流状态，页面提示用户这个站点的流不可用
      commit('CHANGEGETVEDIOSTREAMSTATE404')
    }
  
  },
    // 更新 站点视频流 请求状态， 从 404 到 200
  updateGetStationVideoStreamState200({commit}) {
    commit('CHANGEGETVEDIOSTREAMSTATE200')
  },

  // 加载视频流实时播放页面，params={channel:}
  async onloadVideoStreamPlayer ({commit}, params) {
    
    // 后端获取流
    let resData = await reqStreamPull(params)
    // console.log('请求到的推流信息：', resData)
    if(resData.code === 6000) {
      let reqPlayerInfo = resData.data
      reqPlayerInfo['title'] = constData.categoryData2[reqPlayerInfo.category] + reqPlayerInfo.channel + '号视频'
      commit('ONLOADVIDEOSTREAMPLAYER', { reqPlayerInfo })
    }
  },

   // 关闭视频流详情页，打开视频流网格页面
   closeDetailsLoadVideoGridPages ({commit}) {
    commit('CLOSEDETAILSLOADVIDEOGRIDPAGES')
  },

  // 获取 实时监控页面 事件列表
  async getMonitorEventsTableList ({commit}, params) {
    let resData = await reqEvent(params)
    let monitorEventsData = resData.data.events;
    // console.log("monitorEventsData",monitorEventsData)
    let tableData = monitorEventsData.map((ele, index) => {
          return {
            index: index + 1,
            category: constData2.categoryData[ele.category],
            cause: ele.cause === "0" ? "" : ele.cause,
            event_name: ele.event_name,
            datetime: ele.datetime,
            //需要http地址
            http_url_image: ele.http_url_image,
            http_url_video: ele.http_url_video,
            level: constData2.levelData[ele.level],
          };
        });
    commit('GETMONITOREVENTSTABLELIST', {tableData})
  },

  async getVideolist({commit},params){
    let resData = await reqVideoList(params)
    let videoList = resData.map((item)=>{
      return {
        name:item.filename,
        videoPath:item.url,
        imagePath:"",
        size:"待检测",
        length:"待检测",
        intergrity:"待检测"
      }
    })
    commit("GET_VIDEO_LIST",{videoList})
  },

  handleVideoIntergrity({commit},videos){
    let videoList = videos.map((item)=>{
      return {
        name:item.filename,
        videoPath:item.url,
        imagePath:item.preview,
        size:item.filesize,
        length:item.filetimes,
        intergrity:item.long_video === true?"完整":"不完整"
      }
    })
    commit("GET_VIDEO_LIST",{videoList})
  },

  async getMonitorStatus({commit},params){
    let resData = await reqmonitorStatus(params)
    let monitorStatusData = resData.map((item)=>{
      return {
        channel:item.channel,
        ip:item.ip,
        location:item.location,
        online:item.online ?"在线":"离线"
      }
    })
    commit("GET_MONITOR_STATUS",{monitorStatusData})
  },

  async getVideoInfo({commit},params){
    let resData = await reqmonitorStatus(params)
    if(!params.hasOwnProperty('switch')){
      let videoInfo = resData[0].status
      let historyData = []
      let videoHistory =  resData[0].status.history
      for(var item in videoHistory){
        if(item !== "time"){
          if(item === "2018-01-01 00:00:00"){
            continue
          }
          let status = ""
          switch(videoHistory[item]){
            case 'shack':
                status = "抖动";
                break;
            case 'upheaval':
                status = "剧变";
                break;
            case 'cover':
                status = "遮挡";
                break;
            case 'definition':
                status = "模糊";
                break;
            case 'saturation':
                status = "黑白";
                break;
            case 'static':
                status = "静止";
                break;
          }
          let tempData={
            datetime:item,
            status:status
          }
          historyData.push(tempData)
        }
      }
      
      let videoStatus = {
        content:"",
        online:false
      }
      videoStatus.online = resData[0].online
      if(Object.keys(videoInfo).length === 0){
        videoStatus.content = "正常"
      }
      else{
        if(videoInfo.shack.val === 1){
          videoStatus.content += "抖动 "
        }
        if(videoInfo.upheaval.val === 1){
          videoStatus.content += "剧变 "
        }
        if(videoInfo.cover.val === 1){
          videoStatus.content += "遮挡 "
        }
        if(videoInfo.definition.val === 1){
          videoStatus.content += "模糊 "
        }
        if(videoInfo.saturation.val === 1){
          videoStatus.content += "黑白 "
        }
        if(videoInfo.static.val === 1){
          videoStatus.content += "静止 "
        }
        if(videoStatus.content === ""){
          videoStatus.content = "正常"
        }
      }
      // console.log(videoStatus)
      commit("GET_VIDEO_INFO",{videoStatus,historyData})
    }
  },

  handleTrigger({commit}){
    let videoStatus = {
      content:"饱和度低",
      online :true
    }
    commit("HANDLE_TRIGGER",{videoStatus})
  }
}
